#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <pthread.h>
#include "log.h"

#define LOG_MAX_LEN 128
char g_logBuffer[LOG_MAX_LEN];
char g_logScrollBuffer[10][LOG_MAX_LEN];
char g_logScrollFinalBuffer[10 * LOG_MAX_LEN];
pthread_mutex_t g_logMutex;
pthread_mutex_t g_logScrollMutex;

int LOG(const char *str, ...)
{
	pthread_mutex_lock(&g_logMutex);
	struct timeval logTime;
	gettimeofday(&logTime, NULL);
    va_list args;
    va_start(args, str);
    vsprintf(g_logBuffer, str, args);
    va_end(args);
	
    fprintf(stderr, "[%02d:%02d:%02d:%03d] %s",	logTime.tv_sec / 3600,
												(logTime.tv_sec / 60) % 60,
												logTime.tv_sec % 60,
												logTime.tv_usec / 1000,
												g_logBuffer);
	pthread_mutex_unlock(&g_logMutex);
    return 0;
}

int LOGScroll(int idx, const char *str, ...)
{
	pthread_mutex_lock(&g_logScrollMutex);
	struct timeval logTime;
	gettimeofday(&logTime, NULL);
    va_list args;
    va_start(args, str);
    vsprintf(g_logScrollBuffer[idx], str, args);
    va_end(args);
	pthread_mutex_unlock(&g_logScrollMutex);
    return 0;
}

const char* GetDebugStr()
{
	pthread_mutex_lock(&g_logScrollMutex);
	memset(g_logScrollFinalBuffer, 0, sizeof(g_logScrollFinalBuffer));
	int isFirstLine = 1;
	for (int cnt = 0; cnt < 10; cnt++) {
		if (strlen(g_logScrollBuffer[cnt]) == 0) {
			continue;
		}
		if (isFirstLine) {
			isFirstLine = 0;
		} else {
			strcat(g_logScrollFinalBuffer, "\n");
		}
		strcat(g_logScrollFinalBuffer, g_logScrollBuffer[cnt]);
	}
	pthread_mutex_unlock(&g_logScrollMutex);
	return g_logScrollFinalBuffer;
}

float TimeDiffMillSec(struct timeval tm1, struct timeval tm2)
{
	return (tm1.tv_sec - tm2.tv_sec) * 1000.0f + tm1.tv_usec / 1000.0f - tm2.tv_usec / 1000.0f;
}